package com.itheima.youdianda.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.youdianda.common.Result;
import com.itheima.youdianda.domain.YddUser;
import com.itheima.youdianda.service.YddUserService;
import com.itheima.youdianda.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 前台登录
 */
@RestController
@RequestMapping("/frame/home")
public class HomeLoginController {
    @Autowired
    private YddUserService userService;

    // TODO: 2022/9/9 登录路径有问题
    @PostMapping("/index/login")
    public Result login(@RequestBody Map map) {
        String mobile = map.get("mobile").toString();
        String password = DigestUtils.md5DigestAsHex(map.get("password").toString().getBytes());
        LambdaQueryWrapper<YddUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YddUser::getMobile, mobile);
        YddUser user = userService.getOne(wrapper);
        HashMap<String, Object> ret = new HashMap<>();
        if (user != null && user.getPassword().equals(password)) {
            HashMap<String, Object> tokenMap = new HashMap<>();
            tokenMap.put("id", user.getId());
            String token = JwtUtils.getToken(tokenMap);
            ret.put("token", token);
            return Result.ok(ret);
        } else {
            return Result.error("登陆失败");
        }
    }



}
